const Category = require("../models/categoryModel");
const SubCategory = require("../models/subCategoryModel");

// CREATE Category
const createCategory = async (req, res) => {
  try {
    let { name, description, subCategories = [], status = "Active" } = req.body;

    if (!name) {
      return res.status(400).json({ message: "Category name is required" });
    }

    const newCategory = new Category({ name, description, subCategories, status });
    const result = await newCategory.save();
    res.status(201).json({ message: "Category created successfully", data: result });
  } catch (error) {
    res.status(400).json({ message: "Error creating category", error: error.message });
  }
};

// GET All Categories
const getAllCategories = async (req, res) => {
  try {
    const categories = await Category.find().sort({ name: 1 });
    res.status(200).json(categories);
  } catch (error) {
    res.status(400).json({ message: "Error fetching categories", error: error.message });
  }
};

// GET Single Category
const getCategoryById = async (req, res) => {
  try {
    const category = await Category.findById(req.params.id);
    if (!category) {
      return res.status(404).json({ message: "Category not found" });
    }
    res.status(200).json(category);
  } catch (error) {
    res.status(400).json({ message: "Error fetching category", error: error.message });
  }
};

// UPDATE Category
const updateCategory = async (req, res) => {
  try {
    const { name, description, subCategories, status } = req.body;
    const updatedCategory = await Category.findByIdAndUpdate(
      req.params.id,
      { name, description, subCategories, status },
      { new: true }
    );
    if (!updatedCategory) {
      return res.status(404).json({ message: "Category not found" });
    }
    res.status(200).json({ message: "Category updated", data: updatedCategory });
  } catch (error) {
    res.status(400).json({ message: "Error updating category", error: error.message });
  }
};

// DELETE Category
const deleteCategory = async (req, res) => {
  try {
    const deletedCategory = await Category.findByIdAndDelete(req.params.id);
    if (!deletedCategory) {
      return res.status(404).json({ message: "Category not found" });
    }
    res.status(200).json({ message: "Category deleted" });
  } catch (error) {
    res.status(400).json({ message: "Error deleting category", error: error.message });
  }
};

// CREATE SubCategory
const createSubCategory = async (req, res) => {
  try {
    const { name, description, category, status } = req.body;

    const parentCategory = await Category.findById(category);
    if (!parentCategory) {
      return res.status(400).json({ success: false, message: "Parent category not found" });
    }

    const newSubCategory = new SubCategory({ name, description, category, status });
    const result = await newSubCategory.save();

    parentCategory.subCategories.push(result._id);
    await parentCategory.save();

    res.status(201).json({ success: true, message: "SubCategory created successfully", data: result });
  } catch (error) {
    res.status(400).json({ success: false, message: "Error creating subcategory", error: error.message });
  }
};

// GET All SubCategories
const getAllSuCategories = async (req, res) => {
  try {
    console.log("✅ getAllSubCategories function called!");
    const subCategories = await SubCategory.find();
    console.log("✅ Found subcategories:", subCategories);
    res.status(200).json({ subCategories });
  } catch (error) {
    console.error("❌ Error Fetching Subcategories:", error.message);
    res.status(400).json({ message: "Error fetching subcategories", error: error.message });
  }
};

// GET SubCategories for a Specific Category
const getSubCategories = async (req, res) => {
  try {
    // Find the category by ID and populate the subCategories field
    const category = await Category.findById(req.params.id).populate("subCategories");
    if (!category) {
      return res.status(404).json({ message: "Category not found" });
    }
    // Return the populated subCategories documents
    res.status(200).json({ subCategories: category.subCategories });
  } catch (error) {
    res.status(400).json({ message: "Error fetching subcategories", error: error.message });
  }
};

const updateSubCategory = async (req, res) => {
  try {
    const { id } = req.params;
    const { name, description, status } = req.body;
    // You might want to validate that the subcategory exists
    const updatedSubCategory = await SubCategory.findByIdAndUpdate(
      id,
      { name, description, status },
      { new: true }
    );
    if (!updatedSubCategory) {
      return res.status(404).json({ message: "SubCategory not found" });
    }
    res.status(200).json({ message: "SubCategory updated successfully", data: updatedSubCategory });
  } catch (error) {
    res.status(400).json({ message: "Error updating subcategory", error: error.message });
  }
};

// Delete SubCategory
const deleteSubCategory = async (req, res) => {
  try {
    const { id } = req.params;
    const deleted = await SubCategory.findByIdAndDelete(id);
    if (!deleted) {
      return res.status(404).json({ message: "SubCategory not found" });
    }
    // Optionally, remove the subcategory reference from the parent Category as well
    await Category.findByIdAndUpdate(deleted.category, {
      $pull: { subCategories: deleted._id },
    });
    res.status(200).json({ message: "SubCategory deleted successfully" });
  } catch (error) {
    res.status(400).json({ message: "Error deleting subcategory", error: error.message });
  }
};

// GET Single SubCategory by ID
const getSubCategoryById = async (req, res) => {
  try {
    const subCategory = await SubCategory.findById(req.params.id);
    if (!subCategory) {
      return res.status(404).json({ message: "SubCategory not found" });
    }
    res.status(200).json(subCategory);
  } catch (error) {
    res.status(400).json({ message: "Error fetching subcategory", error: error.message });
  }
};


module.exports = {
  createCategory,
  getAllCategories,
  getCategoryById,
  updateCategory,
  deleteCategory,
  createSubCategory,
  getSubCategories,
  updateSubCategory,
  deleteSubCategory,
  getAllSuCategories,
  getSubCategoryById,
};
